package jkws

import (
	"jkgo/jk/jklog"
	"net/http"
	"strconv"

	"golang.org/x/net/websocket"
)

// CMWSHandler base of weboscket handler
type CMWSHandler struct {
	addr string
	port int
}

// NewCMWSHandler create one cmwshandler
func NewCMWSHandler(addr string, port int) (*CMWSHandler, error) {
	ws := &CMWSHandler{
		addr: addr,
		port: port,
	}

	return ws, nil
}

// Add pair of url and handler function
func (ws *CMWSHandler) Add(url string, msgDeal func(*websocket.Conn)) {
	http.Handle(url, websocket.Handler(msgDeal))
}

// Start start to listen on special port
func (ws *CMWSHandler) Start() error {
	lis := ws.addr + ":" + strconv.Itoa(ws.port)
	jklog.L().Debugln("listen websocket with ", lis)
	err := http.ListenAndServe(lis, nil)
	if err != nil {
		jklog.L().Errorln(err)
		return err
	}
	return nil
}

func (ws *CMWSHandler) StartTls(permfile, keyfile string) error {
	lis := ws.addr + ":" + strconv.Itoa(ws.port)
	jklog.L().Debugln("listen websocket with tls ", lis)
	err := http.ListenAndServeTLS(lis, permfile, keyfile, nil)
	if err != nil {
		jklog.L().Errorln(err)
		return err
	}
	return nil
}

// Read read message
func (ws *CMWSHandler) Read(wc *websocket.Conn, data []byte) (int, error) {
	return wc.Read(data)
}

// Write write message to special socket wc
func (ws *CMWSHandler) Write(wc *websocket.Conn, data []byte) (int, error) {
	return wc.Write(data)
}
